<template>
  <view class="cart">
    <view class="cart-header">
      <view class="checkbox">
        <checkbox v-model="isAllSelected" @click="selectAll" />
      </view>
      <view>全选</view>
      <view>单价</view>
      <view>数量</view>
    </view>
    <view class="cart-list">
      <view class="cart-item" v-for="(item, index) in cartList" :key="index">
        <view class="checkbox">
          <checkbox v-model="item.isSelected" @click="selectItem(index)" />
        </view>
        <view>{{ item.name }}</view>
        <view>{{ item.price}}</view>
        <view class="button-block">
          <button @click="decreaseQuantity(index)">-</button>
          <button><text>{{ item.quantity }}</text></button>
          <button @click="increaseQuantity(index)">+</button>
        </view>
      </view>
    </view>
    <view class="cart-footer">
      <view class="checkbox">
        <checkbox v-model="isAllSelected" @click="selectAll" />
      </view>
      <view>全选</view>
      <view>合计: {{ total }}</view>
      <view>
        <button>结算</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isAllSelected: false,
      cartList: [
        {
          name: "商品1",
          price: 10,
          quantity: 1,
          isSelected: false
        },
        {
          name: "商品2",
          price: 20,
          quantity: 2,
          isSelected: false
        },
        {
          name: "商品3",
          price: 30,
          quantity: 3,
          isSelected: false
        }
      ]
    };
  },
  computed: {
    total() {
      let total = 0;
      for (let item of this.cartList) {
        if (item.isSelected) {
          total += item.price * item.quantity;
        }
      }
      return total;
    }
  },
  methods: {
    selectAll() {
      this.isAllSelected = !this.isAllSelected;
      for (let item of this.cartList) {
        item.isSelected = this.isAllSelected;
      }
    },
    selectItem(index) {
      this.cartList[index].isSelected = !this.cartList[index].isSelected;
      this.checkAllSelected();
    },
    checkAllSelected() {
      let allSelected = true;
      for (let item of this.cartList) {
        if (!item.isSelected) {
          allSelected = false;
          break;
        }
      }
      this.isAllSelected = allSelected;
    },
    increaseQuantity(index) {
      this.cartList[index].quantity++;
    },
    decreaseQuantity(index) {
      if (this.cartList[index].quantity > 1) {
        this.cartList[index].quantity--;
      }
    }
  }
};
</script>

<style>
.cart {
  padding: 20px;
}

.cart-header,
.cart-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}
.button-block{
  display: flex;
}

.cart-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.checkbox {
  margin-right: 10px;
}
</style>
